package com.ruoyi.feike.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.feike.domain.*;
import com.ruoyi.feike.domain.vo.ContractRecord;
import com.ruoyi.feike.mapper.ContractRecordMapper;
import com.ruoyi.feike.mapper.CreditConditionMapper;
import com.ruoyi.feike.mapper.ProposalByCommericalAndMarketingMapper;
import com.ruoyi.feike.mapper.SecuritiesMapper;
import com.ruoyi.feike.service.IBasicInformationService;
import com.ruoyi.feike.service.IContractRecordSerivce;
import com.ruoyi.feike.service.IDealerInformationService;
import com.ruoyi.system.mapper.SysDictDataMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
@Slf4j
public class ContractRecordSerivceImpl implements IContractRecordSerivce {


    @Autowired
    private ContractRecordMapper contractRecordMapper;

    @Autowired
    private ProposalByCommericalAndMarketingMapper proposalByCommericalAndMarketingMapper;

    @Autowired
    private CreditConditionMapper creditConditionMapper;

    @Autowired
    private SecuritiesMapper securitiesMapper;

    @Autowired
    private SysDictDataMapper dictDataMapper;

    @Autowired
    private IBasicInformationService basicInformationService;

    @Autowired
    private IDealerInformationService dealerInformationService;


    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】ID
     * @return 【请填写功能名称】
     */
    @Override
    public ContractRecord selectContractRecordById(Long id)
    {
        return contractRecordMapper.selectHContractRecordById(id);
    }

    @Override
    public ContractRecord selectContractRecordThreeListById(Long id)
    {
        return contractRecordMapper.selectContractRecordThreeListById(id);
    }
    /**
     * 查询【请填写功能名称】列表
     *
     * @param contractRecord 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<ContractRecord> selectContractRecordList(ContractRecord contractRecord)
    {
        return contractRecordMapper.selectContractRecordList(contractRecord);
    }

    @Override
    public List<ContractRecord> selectContractRecordList2(ContractRecord contractRecord)
    {
        return contractRecordMapper.selectContractRecordList2(contractRecord);
    }


    @Override
    public List<ContractRecord> selectContractRecordThreeList(ContractRecord contractRecord)
    {
        return contractRecordMapper.selectContractRecordThreeList(contractRecord);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param contractRecord 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertContractRecord(ContractRecord contractRecord)
    {
        return contractRecordMapper.insertContractRecord(contractRecord);
    }

    @Override
    public int insertContractRecordThree(ContractRecord contractRecord)
    {
        return contractRecordMapper.insertContractRecordThree(contractRecord);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param contractRecord 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateContractRecord(ContractRecord contractRecord)
    {
        return contractRecordMapper.updateContractRecord(contractRecord);
    }

    @Override
    public int updateContractRecordThree(ContractRecord contractRecord)
    {
        return contractRecordMapper.updateContractRecordThree(contractRecord);
    }


    @Override
    public int updateContractRecordThree2(ContractRecord contractRecord)
    {
        return contractRecordMapper.updateContractRecordThree2(contractRecord);
    }

    @Override
    public int updateContractRecord2(ContractRecord contractRecord)
    {
        return contractRecordMapper.updateContractRecord2(contractRecord);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】ID
     * @return 结果
     */
    @Override
    public int deleteContractRecordByIds(Long[] ids)
    {
        return contractRecordMapper.deleteContractRecordByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】ID
     * @return 结果
     */
    @Override
    public int deleteContractRecordById(Long id)
    {
        return contractRecordMapper.deleteContractRecordById(id);
    }

    @Override
    public int update(DealercodeContract dealercodeContract) {
        ContractRecord contractRecord = new ContractRecord();
        contractRecord.setSector(dealercodeContract.getSector());
        contractRecord.setContracttype(dealercodeContract.getContractName());
        contractRecord.setLimitType(dealercodeContract.getLimitType());
        //contractRecord.setDealercode(applac.getDealerCode());
        contractRecord.setDealername(dealercodeContract.getDealerNameCN());
        contractRecord.setInstanceid(dealercodeContract.getInstanceId()+"_1");
        Long sumFacilityamount =0L;
        if(dealercodeContract.getSector().contains("Naveco") ||dealercodeContract.getSector().contains("NAVECO")){
            if(dealercodeContract.getLimitType().equals("NORMAL") ||dealercodeContract.getLimitType().equals("Normal")) {
                ProposalByCommericalAndMarketing approvedLimitAndConditionTemp = new ProposalByCommericalAndMarketing();
                approvedLimitAndConditionTemp.setInstanceId(dealercodeContract.getInstanceId());
                approvedLimitAndConditionTemp.setDealername(dealercodeContract.getDealerNameCN());
                approvedLimitAndConditionTemp.setSector(dealercodeContract.getSector());
                List<ProposalByCommericalAndMarketing> approvedLimitAndConditionTemps = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingList(approvedLimitAndConditionTemp);
                for (ProposalByCommericalAndMarketing limitAndConditionTemp : approvedLimitAndConditionTemps) {
                    if(limitAndConditionTemp.getLimitType()!=null && limitAndConditionTemp.getLimitType().equals("NORMAL")){
                        if(limitAndConditionTemp.getProposalLimit()!=null){
                            sumFacilityamount = sumFacilityamount+limitAndConditionTemp.getProposalLimit();
                        }
                    }
                    if(limitAndConditionTemp.getLimitType()!=null && limitAndConditionTemp.getLimitType().equals("CB")){
                        if(limitAndConditionTemp.getProposalLimit()!=null){
                            sumFacilityamount = sumFacilityamount+limitAndConditionTemp.getProposalLimit();
                        }
                    }
                }
            }else{
                ProposalByCommericalAndMarketing approvedLimitAndConditionTemp = new ProposalByCommericalAndMarketing();
                approvedLimitAndConditionTemp.setInstanceId(dealercodeContract.getInstanceId());
                approvedLimitAndConditionTemp.setDealername(dealercodeContract.getDealerNameCN());
                approvedLimitAndConditionTemp.setSector(dealercodeContract.getSector());
                approvedLimitAndConditionTemp.setLimitType(dealercodeContract.getLimitType());
                List<ProposalByCommericalAndMarketing> approvedLimitAndConditionTemps = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingList(approvedLimitAndConditionTemp);
                if(approvedLimitAndConditionTemps!=null && approvedLimitAndConditionTemps.size()>0 ){
                    ProposalByCommericalAndMarketing proposalByCommericalAndMarketing = approvedLimitAndConditionTemps.get(0);
                    if(proposalByCommericalAndMarketing!=null && proposalByCommericalAndMarketing.getProposalLimit()!=null){
                        sumFacilityamount = sumFacilityamount+proposalByCommericalAndMarketing.getProposalLimit();
                    }
                }
            }
        }else{
            ProposalByCommericalAndMarketing approvedLimitAndConditionTemp = new ProposalByCommericalAndMarketing();
            approvedLimitAndConditionTemp.setInstanceId(dealercodeContract.getInstanceId());
            approvedLimitAndConditionTemp.setDealername(dealercodeContract.getDealerNameCN());
            approvedLimitAndConditionTemp.setSector(dealercodeContract.getSector());
            approvedLimitAndConditionTemp.setLimitType(dealercodeContract.getLimitType());
            List<ProposalByCommericalAndMarketing> approvedLimitAndConditionTemps = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingList(approvedLimitAndConditionTemp);
            if(approvedLimitAndConditionTemps!=null && approvedLimitAndConditionTemps.size()>0 ){
                ProposalByCommericalAndMarketing proposalByCommericalAndMarketing = approvedLimitAndConditionTemps.get(0);
                if(proposalByCommericalAndMarketing!=null && proposalByCommericalAndMarketing.getProposalLimit()!=null){
                    sumFacilityamount = sumFacilityamount+proposalByCommericalAndMarketing.getProposalLimit();
                }
            }
        }
        if(StringUtils.isNotNull(sumFacilityamount)){
            contractRecord.setFacilityamount(sumFacilityamount.toString());
        }
        contractRecord.setContractno(dealercodeContract.getContract());

        CreditCondition creditCondition = new CreditCondition();
        creditCondition.setDealername(dealercodeContract.getDealerNameCN());
        creditCondition.setSector(dealercodeContract.getSector());
        creditCondition.setLimittype(dealercodeContract.getLimitType());
        creditCondition.setInstanceid(dealercodeContract.getInstanceId());
        List<CreditCondition> creditConditions = creditConditionMapper.selectCreditConditionList(creditCondition);
        if(creditConditions!=null && creditConditions.size()>0){
            CreditCondition creditCondition1 = creditConditions.get(0);
            if(creditCondition1!=null && creditCondition1.getExpireddate()!=null){
                contractRecord.setExpirydate(creditCondition1.getExpireddate());
            }
        }
        //查询
        StringBuilder stringBuilderPersonal = new StringBuilder();
        StringBuilder stringBuilderCompany = new StringBuilder();
        Securities securities = new Securities();
        securities.setInstanceId(dealercodeContract.getInstanceId());
        securities.setDealername(dealercodeContract.getDealerNameCN());
        List<Securities> securitiesList = securitiesMapper.selectSecuritiesListTypeIsnotnull(securities);
        for (Securities securitiesTemp : securitiesList) {
            if(null != securitiesTemp.getGuaranteeType()){
                if(securitiesTemp.getGuaranteeType().equals("personal")){
                    if(securitiesTemp.getProposalNameCN()!=null){
                        stringBuilderPersonal.append(securitiesTemp.getProposalNameCN()).append(",");
                    }
                }
                if(securitiesTemp.getGuaranteeType().equals("corporate")){
                    if(securitiesTemp.getProposalNameCN()!=null){
                        stringBuilderCompany.append(securitiesTemp.getProposalNameCN()).append(",");
                    }
                }
            }

        }
        if (stringBuilderPersonal.length()>0) {
            stringBuilderPersonal.deleteCharAt(stringBuilderPersonal.length() - 1);
            contractRecord.setPersonalguarantee(stringBuilderPersonal.toString());
        }else{
            contractRecord.setPersonalguarantee(null);
        }
        if (stringBuilderCompany.length()>0) {
            stringBuilderCompany.deleteCharAt(stringBuilderCompany.length() - 1);
            contractRecord.setCompanyguarantee(stringBuilderCompany.toString());
        }else{
            contractRecord.setCompanyguarantee(null);
        }
        String dictLabel = dictDataMapper.selectDictLabel("h_basic_contract_priority", dealercodeContract.getPriority());
        contractRecord.setScenario(dictLabel);

        DealerInformation dealerInformation = new DealerInformation();
        dealerInformation.setDealerName(dealercodeContract.getDealerNameCN());
        dealerInformation.setMake(dealercodeContract.getSector());
        List<DealerInformation> dealerInformations = dealerInformationService.selectDealerInformationList(dealerInformation);
        if(!StringUtils.isEmpty(dealerInformations) && dealerInformations.size()>0){
            DealerInformation dealerInformation1 = dealerInformations.get(0);
            contractRecord.setDealercode(dealerInformation1.getDealerCode());
            contractRecord.setGroupName(dealerInformation1.getGroupName());
        }
        insertContractRecord(contractRecord);
        return 0;
    }

    /**
     * 导入用户数据
     *
     * @param userList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<ContractRecord> userList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new CustomException("导入合同报表数据不能为空！");
        }
        int successNum = 1;
        int failureNum = 0;
        int suNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        // 导入前清表一次
        //plmMapper.deletePlmBy();
//        ArrayList<ContractRecord> contractRecordInsert = new ArrayList<>();
//        ArrayList<ContractRecord> contractRecordsUpdate = new ArrayList<>();
        for (ContractRecord stu : userList)
        {
            try
            {
                List<ContractRecord> repeatPlm = null;
                if(StringUtils.isEmpty(stu.getDealercode())){
                    successMsg.append("<br/>" +"、dealerCode数据不能为空请检查数据");
                    return successMsg.toString();
                }
                if(StringUtils.isNotEmpty(stu.getDealercode())){
                    ContractRecord contractRecord = new ContractRecord();
                    contractRecord.setSector(stu.getSector());
                    contractRecord.setDealername(stu.getDealername());
                    contractRecord.setDealercode(stu.getDealercode());
                    contractRecord.setContracttype(stu.getContracttype());
                    contractRecord.setContractno(stu.getContractno());
                    contractRecord.setIssuedate(stu.getIssuedate());
                    if(StringUtils.isEmpty(stu.getLimitType())){
                        String contractno = stu.getContractno();
                        if(stu.getDealername().equals("人民币循环贷款合同附件三")){
                            stu.setLimitType("Temp");
                        } else if(contractno.contains("DEMO")){
                            stu.setLimitType("Demo");
                        }else if(contractno.contains("CB")){
                            stu.setLimitType("CB");
                        }else{
                            stu.setLimitType("Normal");
                        }
                    }

                    repeatPlm = contractRecordMapper.selectContractRecordListInstanceidNull(contractRecord);
                }
                //增量导入，不存在就新增
                if(CollectionUtil.isEmpty(repeatPlm)){
                    this.insertContractRecord(stu);
//                    contractRecordInsert.add(stu);
                    successMsg.append("<br/>" + successNum + "、经销商 " + stu.getDealername() + " 导入成功");
                    suNum++;
                }else {
                    for(ContractRecord record : repeatPlm ){
//                        contractRecordsUpdate.add(record);
                        stu.setId(record.getId());
                        this.updateContractRecord(stu);
                        successMsg.append("<br/>" + successNum+ "、合同号: "+stu.getContractno()+ " 数据重复并覆盖往期数据");
                        suNum++;
                    }
                }
                successNum++;

            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、经销商 " + stu.getDealername() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
//        contractRecordMapper.batchInsert(contractRecordInsert);
//        contractRecordMapper.updateBatchById(contractRecordsUpdate);
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + suNum + " 条不重复数据，数据如下：");
        }
        return successMsg.toString();
    }
}
